package com.leapp.sk.viewdelegate.adapter.im

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.CallBack
import cc.vv.lkbasecomponent.util.LKDateTimeUtil
import cc.vv.lkbasecomponent.util.LKScreenUtil
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.body.LKIMVoiceBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMStatus
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.table.AccountTable
import com.example.mvp.delegate.BaseAdapterDelegate
import com.example.mvp.view.GlideCircleTransform
import com.example.mvp.view.LKCircleImageView
import com.leapp.sk.R
import com.leapp.sk.app.SKApplication
import com.leapp.sk.ui.activity.im.MessageStateActivity
import com.leapp.sk.util.IMDialogUtil
import com.leapp.sk.util.SKTimeUtil
import com.example.util.finallist.*
import com.leapp.sk.util.im.IMVoicePlayer
import java.io.File
import java.io.IOException
import java.util.*

/**
 * 语音类型适配器视图托管类
 * @author  chaohaipeng  on 2018/7/19.
 */
class ChatVoiceAdapterDelegate : BaseAdapterDelegate() {
    /**
     * 图片加载操作
     */
    var mRequestOptions: RequestOptions = RequestOptions()

    /**
     * 头像加载操作
     */
    var mHeadRequestOptions: RequestOptions = RequestOptions()
    val text: TextView?=null
    override fun getOptionsMenuId(): Int {
        return 0
    }

    override fun initWidget() {
    }

    override fun onDestroy() {
    }

    override fun initLayoutRes(): Int {
        return R.layout.sk_chat_voice_message

    }
    /**
     * 设置收到消息View
     */
    fun setRecerveView(context: Context,lkimMessage: LKIMMessage,timeInterval:Int,position: Int){
        val v_scvm_receive_root=getView<RelativeLayout>(R.id.v_scvm_receive_root)
        val rl_scvm_send_root=getView<RelativeLayout>(R.id.rl_scvm_send_root)
        val tv_scvm_receive_msgTime_receive=getView<TextView>(R.id.tv_scvm_receive_msgTime_receive)
        tv_scvm_receive_msgTime_receive.visibility=View.VISIBLE
        v_scvm_receive_root.visibility=View.VISIBLE
        rl_scvm_send_root.visibility=View.GONE
        setRecerveData(context,lkimMessage,timeInterval,position)
    }
    /**
     * 设置头像和昵称
     */
    fun setHead(context: Context,headUrl:String?,headImage: LKCircleImageView){
        val tag = headImage.getTag(R.id.tag_head)
        if ( tag==null||!tag?.equals(headUrl)){
            val mRequestManager = Glide.with(context)
            mHeadRequestOptions?.diskCacheStrategy(DiskCacheStrategy.NONE)
            mHeadRequestOptions?.skipMemoryCache(true)
            mHeadRequestOptions?.error(R.mipmap.icon_defout_head)
            mHeadRequestOptions?.transforms(GlideCircleTransform(context))
            mRequestManager?.load(headUrl)
                    ?.thumbnail(0.2f)
                    ?.apply(mHeadRequestOptions)
                    ?.into(headImage)
            headImage.setTag(R.id.tag_head,headUrl)
        }
    }

    /**
     * 设置收到消息数据
     */
    private fun setRecerveData(context: Context,lkimMessage: LKIMMessage,timeInterval:Int,position: Int){
        val tv_scvm_time=getView<TextView>(R.id.tv_scvm_time)
        val iv_scvm_receive_image=getView<ImageView>(R.id.iv_scvm_receive_image)
        val tv_scvm_receive_nick=getView<TextView>(R.id.tv_scvm_receive_nick)
        val lav_scvm_receive_avatar=getView<LKCircleImageView>(R.id.lav_scvm_receive_avatar)
        val rl_scvm_receive_content=getView<RelativeLayout>(R.id.rl_scvm_receive_content)
        val tv_scvm_receive_msgTime_receive=getView<TextView>(R.id.tv_scvm_receive_msgTime_receive)
        iv_scvm_receive_image.setImageResource(R.drawable.animation_imreceive_voice_play)
        val isPlay = lkimMessage.getAttribute(IMExtKey.EXTKEY_ISPLAY, IS_FASE)
        tv_scvm_receive_nick.visibility=View.VISIBLE
        val headUrl= lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR,"")
        val nick= lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK,"")

        val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
        if (accountTable==null||!TextUtils.equals( accountTable.avatar,headUrl)||!TextUtils.equals( accountTable.nick,nick)){
            val accountTable = AccountTable()
            accountTable.avatar=headUrl
            accountTable.nick=nick
            accountTable.account=lkimMessage.toAccount
            tv_scvm_receive_nick.text=nick
            AccountDao.getInstance().createOrUpdate(accountTable)
            setHead(context,headUrl,lav_scvm_receive_avatar)
        }else{
            val avatar = if (null == accountTable) "" else accountTable.avatar
            val nick = if (null == accountTable) LKStringUtil.getString(R.string.app_name) else accountTable.nick
            tv_scvm_receive_nick.text=nick
            setHead(context,avatar,lav_scvm_receive_avatar)
        }


        if (TextUtils.equals(isPlay, IS_TRUE)) {
            val animationDrawable = iv_scvm_receive_image.getDrawable() as AnimationDrawable
            animationDrawable?.start()
        }
        tv_scvm_time.text= LKDateTimeUtil.formatDateTime(lkimMessage.msgTime,"")
        isShowTime(tv_scvm_time, timeInterval, lkimMessage.msgTime, position)
        var lkimVoiceBody: LKIMVoiceBody?=null
        try {
            lkimVoiceBody= lkimMessage.lkIMBody as LKIMVoiceBody
        }catch (e:Exception){
            lkimVoiceBody
        }
        if (lkimVoiceBody!=null){
            val duration = lkimVoiceBody?.duration
            tv_scvm_receive_msgTime_receive.text="$duration\""
            initBodyViewWidth(rl_scvm_receive_content, lkimVoiceBody.duration)
            rl_scvm_receive_content.setOnClickListener(object :View.OnClickListener{
                override fun onClick(p0: View?) {
                    downVoiceFile(iv_scvm_receive_image,lkimMessage)
                }
            })
            val activity=  context as Activity
            rl_scvm_receive_content.setOnLongClickListener(View.OnLongClickListener {
                IMDialogUtil.getInstance().longClickEvent(activity,lkimMessage)
                true
            })
        }


    }
    /**
     * 发送数据View
     */
    fun setSendDataView(context: Context, lkimMessage: LKIMMessage, timeInterval:Int, position: Int){
        val v_scvm_receive_root=getView<RelativeLayout>(R.id.v_scvm_receive_root)
        val rl_scvm_send_root=getView<RelativeLayout>(R.id.rl_scvm_send_root)
        val tv_scvm_send_msgStatus_def_yes=getView<TextView>(R.id.tv_scvm_send_msgStatus_def_yes)
        val pb_scvm_send_im_sending=getView<ProgressBar>(R.id.pb_scvm_send_im_sending)
        val iv_scvm_send_im_fail=getView<ImageView>(R.id.iv_scvm_send_im_fail)
        val tv_scvm_receive_msgTime_receive=getView<TextView>(R.id.tv_scvm_receive_msgTime_receive)
        tv_scvm_receive_msgTime_receive.visibility=View.GONE
        rl_scvm_send_root.visibility= View.VISIBLE
        v_scvm_receive_root.visibility=View.GONE
        if (lkimMessage.lkimStatus== LKIMStatus.FAIL){
            tv_scvm_send_msgStatus_def_yes.visibility= View.INVISIBLE
            pb_scvm_send_im_sending.visibility= View.INVISIBLE
            iv_scvm_send_im_fail.visibility= View.VISIBLE
        }else if (lkimMessage.lkimStatus== LKIMStatus.SUCCESS){
            setReadInfo(context,lkimMessage)
        }else if (lkimMessage.lkimStatus== LKIMStatus.INPROGRESS){
            tv_scvm_send_msgStatus_def_yes.visibility= View.INVISIBLE
            iv_scvm_send_im_fail.visibility= View.INVISIBLE
            pb_scvm_send_im_sending.visibility= View.VISIBLE
        }
        setSendData(context,lkimMessage,timeInterval,position)
    }


    /**
     * 设置已读信息
     */
    fun setReadInfo(context: Context,lkimMessage: LKIMMessage){
        val tv_scvm_send_msgStatus_def_yes=getView<TextView>(R.id.tv_scvm_send_msgStatus_def_yes)
        val pb_scvm_send_im_sending=getView<ProgressBar>(R.id.pb_scvm_send_im_sending)
        val iv_scvm_send_im_fail=getView<ImageView>(R.id.iv_scvm_send_im_fail)
        if (LKIMChatType.GroupChat==lkimMessage.lkimChatType){
            val groupMemerCount = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_GROUPMEMERCOUNT, SkKey.BTKEY_String_0))
            val readMembersCount = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERSCOUNT, SkKey.BTKEY_String_0))
            val unReadMemberCount = groupMemerCount - readMembersCount
            if (unReadMemberCount > 0) {
                tv_scvm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_4390E1))
                tv_scvm_send_msgStatus_def_yes.text=String.format(Locale.CHINESE, LKStringUtil.getString(R.string.string_im_unread_portion), unReadMemberCount)
            } else {
                tv_scvm_send_msgStatus_def_yes.text=context.resources.getString(R.string.string_im_read)
                tv_scvm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_C0C0C0))
            }
        }else{
            if (TextUtils.equals(lkimMessage.isAcked,"1")){
                tv_scvm_send_msgStatus_def_yes.text=context.resources.getString(R.string.string_im_read)
                tv_scvm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_C0C0C0))
            }else{
                tv_scvm_send_msgStatus_def_yes.text=context.resources.getString(R.string.string_im_unread)
                tv_scvm_send_msgStatus_def_yes.setTextColor(ContextCompat.getColor(context,R.color.color_4390E1))
            }

        }
        tv_scvm_send_msgStatus_def_yes.visibility=View.VISIBLE
        pb_scvm_send_im_sending.visibility=View.INVISIBLE
        iv_scvm_send_im_fail.visibility=View.INVISIBLE
    }



    /**
     * 发送数据
     */
    fun setSendData(context: Context, lkimMessage: LKIMMessage, timeInterval:Int, position: Int){
        val tv_scvm_time=getView<TextView>(R.id.tv_scvm_time)
        val iv_scvm_send_image=getView<ImageView>(R.id.iv_scvm_send_image)
        val rl_scvm_send_content=getView<RelativeLayout>(R.id.rl_scvm_send_content)
        val tv_scvm_send_duration=getView<TextView>(R.id.tv_scvm_send_duration)
        iv_scvm_send_image.setImageResource(R.drawable.animation_imsend_voice_play)
        val isPlay = lkimMessage.getAttribute(IMExtKey.EXTKEY_ISPLAY, IS_FASE)
        val lav_scvm_send_avatar=getView<LKCircleImageView>(R.id.lav_scvm_send_avatar)

        var lkimVoiceBody:LKIMVoiceBody?=null
        try {
            lkimVoiceBody= lkimMessage.lkIMBody as LKIMVoiceBody
        }catch (e:Exception){
            lkimVoiceBody=null
        }
        if (lkimVoiceBody==null){
            return
        }
        val localUrl = lkimVoiceBody.localUrl

        val headUrl= lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR,"")
        val nick= lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK,"")
        val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
        if (accountTable==null){
            accountTable?.avatar=headUrl
            accountTable?.nick=nick
            accountTable?.account=lkimMessage.fromAccount
            setHead(context,headUrl,lav_scvm_send_avatar)
        }else{
            val avatar = if (null == accountTable) "" else accountTable.avatar
            setHead(context,avatar,lav_scvm_send_avatar)
        }
        if (TextUtils.equals(isPlay, IS_TRUE)) {
            val animationDrawable = iv_scvm_send_image.getDrawable() as AnimationDrawable
            animationDrawable?.start()
        }
        tv_scvm_time.text= LKDateTimeUtil.formatDateTime(lkimMessage.msgTime,"")
        isShowTime(tv_scvm_time, timeInterval, lkimMessage.msgTime, position)
        val duration = lkimVoiceBody.duration
        tv_scvm_send_duration.text="$duration\""
        initBodyViewWidth(rl_scvm_send_content, lkimVoiceBody.duration)
        rl_scvm_send_content.setOnClickListener(object :View.OnClickListener{
            override fun onClick(p0: View?) {
                voicePlayer(iv_scvm_send_image,lkimMessage,localUrl,true)
            }
        })
        val activity=  context as Activity
        initEvent(activity,lkimMessage)
    }

    /**
     * 初始化事件
     */
    fun initEvent(context: Activity, lkimMessage: LKIMMessage){
        val tv_scstm_send_msgStatus_def_yes=getView<TextView>(R.id.tv_scvm_send_msgStatus_def_yes)
        val rl_scstm_send_content=getView<RelativeLayout>(R.id.rl_scvm_send_content)
        tv_scstm_send_msgStatus_def_yes.setOnClickListener(object :View.OnClickListener{
            override fun onClick(p0: View?) {
                if (lkimMessage.lkimChatType == LKIMChatType.GroupChat) {
                    val unReadMemberIds = lkimMessage.getAttribute(IMExtKey.EXTKEY_UNREADMEMBERIDS, "")
                    val readMemberIds = lkimMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERIDS, "")
                    val intent = Intent(context, MessageStateActivity::class.java)
                    intent.putExtra(READ_MESSAGE_IDS, readMemberIds)
                    intent.putExtra(UNREAD_MESSAGE_IDS, unReadMemberIds)
                    intent.putExtra(MSG_DATA,lkimMessage)
                    intent.putExtra(GROUP_ID, lkimMessage.toAccount)
                    context?.startActivity(intent)
                }

            }
        })
        rl_scstm_send_content.setOnLongClickListener(View.OnLongClickListener {
            IMDialogUtil.getInstance().longClickEvent(context,lkimMessage)
            true
        })

    }


    /**
     * 下载接收方音频到本地
     *
     * @param remoteUrl
     */
    private fun downVoiceFile(voiceImage:ImageView,lkimMessage: LKIMMessage) {
        var lkimVoiceBody:LKIMVoiceBody?=null
        try {
             lkimVoiceBody= lkimMessage.lkIMBody as LKIMVoiceBody
        }catch (e:Exception){
            lkimVoiceBody=null
        }
        if (lkimVoiceBody==null){
            return
        }

        val voiceDir = SKApplication.getInstance()?.getExternalFilesDir("voice")
        val voiceFile = File(voiceDir, System.currentTimeMillis().toString() + "bt.amr")
        if (!voiceFile.exists()) {
            try {
                voiceFile.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
        LKHttp.downLoadWithGet(lkimVoiceBody.remoteUrl, null, voiceFile.getAbsolutePath(), true, object : CallBack<String>() {
            override fun onDownLoadProgress(url: String?, filePath: String?, progress: Int) {
                super.onDownLoadProgress(url, filePath, progress)
            }

            override fun onDownLoadFailure(url: String?, filePath: String?) {
                super.onDownLoadFailure(url, filePath)

            }

            override fun onDownLoadSuccess(url: String?, filePath: String?) {
                super.onDownLoadSuccess(url, filePath)
                voicePlayer(voiceImage,lkimMessage,voiceFile.absolutePath,false)
            }
        }, false)
    }
    /**
     * 初始化语音消息体控件长度
     *
     * @param contentView
     */
    private fun initBodyViewWidth(contentView: View, duration: Int) {
        val layoutParams = contentView.layoutParams
        val minWidth = LKScreenUtil.dp2px(50f)
        val middleWidth = LKScreenUtil.dp2px(80f)
        val maxWidth = LKScreenUtil.dp2px(120f)
        if (duration <= 10) {
            layoutParams.width = minWidth
        } else if (duration <= 40) {
            layoutParams.width = middleWidth
        } else {
            layoutParams.width = maxWidth
        }
    }


    /**
     * 语音播放
     */
    fun voicePlayer(voiceImage:ImageView,lkimMessage: LKIMMessage,donwLoadVoce:String,isSend:Boolean){


        IMVoicePlayer.getInstance().playUrl(donwLoadVoce, false, object : IMVoicePlayer.PlayerInter {
            override fun onStart() {
                if (isSend){
                    voiceImage.setImageResource(R.drawable.animation_imsend_voice_play)
                }else{
                    voiceImage.setImageResource(R.drawable.animation_imreceive_voice_play)
                }

                val animationDrawable = voiceImage.getDrawable() as AnimationDrawable
                animationDrawable?.start()
                lkimMessage.setAttribute(IMExtKey.EXTKEY_ISPLAY, IS_TRUE)
            }
            override fun onCompletion() {
                val animationDrawable = voiceImage.getDrawable() as AnimationDrawable
                animationDrawable?.stop()
                if (isSend){
                    voiceImage.setImageResource(R.drawable.animation_imsend_voice_play)
                }else{
                    voiceImage.setImageResource(R.drawable.animation_imreceive_voice_play)
                }
                lkimMessage.setAttribute(IMExtKey.EXTKEY_ISPLAY, IS_FASE)
            }

            override fun onError() {
                val animationDrawable = voiceImage.getDrawable() as AnimationDrawable
                animationDrawable?.stop()
                if (isSend){
                    voiceImage.setImageResource(R.drawable.animation_imsend_voice_play)
                }else{
                    voiceImage.setImageResource(R.drawable.animation_imreceive_voice_play)
                }
                lkimMessage.setAttribute(IMExtKey.EXTKEY_ISPLAY, IS_FASE)
            }

            override fun onStop() {
                val animationDrawable = voiceImage.getDrawable() as AnimationDrawable
                animationDrawable?.stop()
                if (isSend){
                    voiceImage.setImageResource(R.drawable.animation_imsend_voice_play)
                }else{
                    voiceImage.setImageResource(R.drawable.animation_imreceive_voice_play)
                }
                lkimMessage.setAttribute(IMExtKey.EXTKEY_ISPLAY,IS_FASE)
            }
        })


    }




    /**
     * 间隔时间处理
     *
     * @param tv_time
     * @param timeInterval
     * @param time
     */
    private fun isShowTime(tv_time: TextView, timeInterval: Int, time: Long, position: Int) {
        if (timeInterval >= 5) {
            val dayOrHours = SKTimeUtil.getDayOrHours(time)
            tv_time.text=dayOrHours
            tv_time.visibility = View.VISIBLE
        } else {
            if (position == 0) {
                val dayOrHours = SKTimeUtil.getDayOrHours(time)
                tv_time.text=dayOrHours
                tv_time.visibility = View.VISIBLE
            } else {
                tv_time.visibility = View.GONE
            }

        }
    }
}